package com.zzj.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;

import java.util.Date;

public class JWTUtil {
    // jwt 加解密类型

    public static final String SECRET_KEY = "1127394608"; //秘钥
    public static final long TOKEN_EXPIRE_TIME = 30 * 60 * 1000; //token过期时间 ms  30min
    public static final long REFRESH_TOKEN_EXPIRE_TIME = 60*110 ; //refreshToken过期时间 s 110min
    public static final String BLACK_KEY ="Token黑名单";
    public static final String PRIVATE_KEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJ2bigtQ9LgnSZLesAUU7BsKKCeaxc/ZyG2DZcmneCRNpQmkK+AWXonVvhkkYaJOrU5xXW2R2qBMNbS5rNcTSMjRrC48Cthby+UnsIdvOtTRvhs93g2v/zGyk2UsxDYzK9HQby8wdhQ0SpJOxHgTkbFgZEezF8n7CbyTUYLgU1IHAgMBAAECgYAd3bKcEFw/ZVqA1WgfnmZbfWI8lwyzJX7gmcy5GN4gawJCQHT8AuEpV3KtiwJhYm1e9waQU9pNFAP9Wk4Rd5sL/pE5oLeYFpGZSHssS2ayfXX5sOSU+FJfQ/G2jDCc2EFidROPs2Q4Nd/hNYRPf7Yg2JI8ps2gBeciz7Z8UNsN6QJBANyXO8kn24cbKzFyWTkOXyijY9gWfyt/+AiAugzigA+m9yZhoY7LSDL0KNvQEI2oO1H+rn0zv1Dwm/9aTPBX+10CQQC26CEOqK0C/rCklUcKBQHpfdgNXL1voQT4MuXgDwo+rtROR+o1QxPcudmetOTFTm+B31ZxO0gqGu0xA65qr9CzAkA+ONJ+XSXJKFq4qd6M/4bL+bqSG1ZnuMMH8veH5uPkhl40j1l449JLvR9BUaE5s/h3mnUxj8UpWZVHI/uL1+VpAkBX/Q1CBwTLxwfk9ObqvAPydhaEPxPmaniAicOp6LJN+z6otdHGc5FPgpxcy7qt7BCaUn08FX+eubtW8+Vo71EfAkEAt1OKScFvQULVpGWHjeofDZNNi/zw1FFeUGTlbARA0IdfPxtLvuMD5Yu6W4WIMZgIb+Ongyq9aHCfE169yTx97A==";
    public static final String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCdm4oLUPS4J0mS3rAFFOwbCignmsXP2chtg2XJp3gkTaUJpCvgFl6J1b4ZJGGiTq1OcV1tkdqgTDW0uazXE0jI0awuPArYW8vlJ7CHbzrU0b4bPd4Nr/8xspNlLMQ2MyvR0G8vMHYUNEqSTsR4E5GxYGRHsxfJ+wm8k1GC4FNSBwIDAQAB";




    private static final String ISSUER = "zWesley"; //签发人



    /**
     * 生成签名
     */
    public static String generateToken(String username){
        Date now = new Date();
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY); //算法

        String token = JWT.create()
                .withIssuer(ISSUER) //签发人
                .withIssuedAt(now) //签发时间
                .withExpiresAt(new Date(now.getTime() + TOKEN_EXPIRE_TIME)) //过期时间
                .withClaim("username", username) //保存身份标识
                .sign(algorithm);
        return token;
    }

    /**
     * 验证token
     */
    public static boolean verify(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY); //算法
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(ISSUER)
                    .build();
            verifier.verify(token);
            return true;
        } catch (Exception ex){
//            ex.printStackTrace();
        }
        return false;
    }

    /**
     * 从token获取username
     */
    public static String getUsername(String token){
        try{
            return JWT.decode(token).getClaim("username").asString();
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return "";
    }
}